//
//  ChatRoomViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/4/6.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "ChatRoomViewController.h"
#import "ChatRoomModel.h"
#import "ChatRoomTableViewCell.h"
#import "MyChatViewController.h"
#import "ChatRoomSearchViewController.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface ChatRoomViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *chatRoomTableView;
@property (nonatomic, strong) NSMutableArray *chatRoomDataArray;

@property (nonatomic, strong) NSTimer *myTimer; // 检查请求是否超时
@property (nonatomic, assign) NSInteger numberOfTime; // 存储请求时间

@end



@implementation ChatRoomViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
    [self.myTimer invalidate];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi修改
    [self changeNavigation];
    // 检查网络并添加数据源
    [self searchNetAndData];
}

// navi的修改
- (void)changeNavigation
{
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationItem.title = @"聊天室";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
    UIImageView *rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    rightImageView.image = [UIImage imageNamed:@"baisesousuokuang-liaotianshi"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightImageView];
    
    UITapGestureRecognizer *rightTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchChatRoom:)];
    [rightImageView addGestureRecognizer:rightTapGes];
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 检查网络并且添加数据源
- (void)searchNetAndData
{
    if ([[[NetStatusHandle shareHandle] getNetStatus] isEqualToString:@"YES"]) {
        [self addData];
        // 建立计数器
        self.myTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(goTimeOnLiaoTianShi:) userInfo:nil repeats:YES];
        self.numberOfTime = 0;
        [[NSRunLoop currentRunLoop] addTimer:self.myTimer forMode:NSRunLoopCommonModes];
        // 开启加载动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
    } else {
        NSLog(@"没有网络");
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kNoNetNoRefresh ToView:self];
    }

}

#pragma mark - 聊天室的计时器
- (void)goTimeOnLiaoTianShi:(NSTimer *)timer
{
    self.numberOfTime++;
    NSLog(@"聊天室页请求时间:%ld", self.numberOfTime);
    if (self.numberOfTime > kZGWQingQiuChaoShi) {
        NSLog(@"聊天室页请求超时");
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kQingQiuChaoShiNoReFresh ToView:self];
    }
}



#pragma mark - 搜索聊天室
- (void)searchChatRoom:(UITapGestureRecognizer *)tapGes
{
    ChatRoomSearchViewController *chatRoomSearchVC = [[ChatRoomSearchViewController alloc] init];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:chatRoomSearchVC];
    chatRoomSearchVC.searchChatRoomDataArray = self.chatRoomDataArray;
    [self presentViewController:naVC animated:YES completion:nil];
}

#pragma mark - 建立数据源
- (void)addData
{
    // 聊天室信息url
    NSString *getAllChatroomUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWGetAllChatroomInformation, kCurrentUserToken];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:getAllChatroomUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 暂停计时器
        [self.myTimer invalidate];
        self.numberOfTime = 0;
       
        if (!responseObject) {
            return;
        }
        NSArray *chatRoomArray = [NSArray arrayWithArray:responseObject];
        NSLog(@"聊天室数组 = %@", chatRoomArray);
        
        self.chatRoomDataArray = [NSMutableArray array];
        for (NSDictionary *chatRoomDic in chatRoomArray) {
            ChatRoomModel *chatroomModel = [[ChatRoomModel alloc] init];
            [chatroomModel setValuesForKeysWithDictionary:chatRoomDic];
            [self.chatRoomDataArray addObject:chatroomModel];
        }
        
        //  布局
        [self addMySubview];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kHuoQuDataShiBaiNoRefresh ToView:self];
        // 暂停计时器
        [self.myTimer invalidate];
        self.numberOfTime = 0;

    }];
    
    
    
    
    
//    // 模拟数据
//    self. chatRoomDataArray = [NSMutableArray array];
//    NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"心脏病", @"_name", @"本聊天室是为心脏病而建立", @"_introduce" , nil];
//    NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"心肌梗塞", @"_name", @"本聊天室是为心肌梗塞而建立", @"_introduce" , nil];
//    NSDictionary *dic3 = [NSDictionary dictionaryWithObjectsAndKeys:@"糖尿病", @"_name", @"本聊天室是为糖尿病而建立", @"_introduce" , nil];
//    NSArray *tempArray = [NSMutableArray arrayWithObjects:dic1, dic2, dic3, nil];
//    for (NSDictionary *tempDic in tempArray) {
//        ChatRoomModel *model = [[ChatRoomModel alloc] init];
//        [model setValuesForKeysWithDictionary:tempDic];
//        [self.chatRoomDataArray addObject:model];
//    }

}

#pragma mark - 布局
- (void)addMySubview
{
    self.chatRoomTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.chatRoomTableView.backgroundColor = [UIColor whiteColor];
    self.chatRoomTableView.bounces = NO;
    self.chatRoomTableView.dataSource = self;
    self.chatRoomTableView.delegate = self;
    [self.view addSubview:_chatRoomTableView];
     [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addTopGrayAlertWithContent:@"聊天室列表同步成功" toView:self];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chatRoomDataArray.count;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 动态高度
    ChatRoomTableViewCell *cell = (ChatRoomTableViewCell *)[self tableView:self.chatRoomTableView cellForRowAtIndexPath:indexPath];
    return cell.chatRoomIntroduce.bottom + 10 * kAdjustParamater;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"chatRoomCell";
    ChatRoomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ChatRoomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    [cell.joinChatRoomButton addTarget:self action:@selector(JoinChat:) forControlEvents:UIControlEventTouchUpInside];
    cell.joinChatRoomButton.tag = indexPath.row + 100;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.chatRoomDataArray.count > indexPath.row) {
        cell.model = self.chatRoomDataArray[indexPath.row];
    }
    return cell;
}

#pragma mark - 加入聊天室
- (void)JoinChat:(UIButton *)button
{
    
    NSInteger row = button.tag - 100;
    ChatRoomModel *model = self.chatRoomDataArray[row];
    
    MyChatViewController *myChatVC = [[MyChatViewController alloc] init];
    myChatVC.conversationType = ConversationType_CHATROOM;
    myChatVC.title = model.name;
    myChatVC.targetId = [NSString stringWithFormat:@"%@", model.chatroomID];
    myChatVC.defaultHistoryMessageCountOfChatRoom = 20;
    [self.navigationController pushViewController:myChatVC animated:YES];
    
//    // 用户加入聊天室
//    NSString *userJoinChatRoomUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWUserJoinChatRoom, kCurrentUserToken];
//    NSString *chatRoomID = [NSString stringWithFormat:@"%@", model.chatroomID];
//    NSDictionary *paramaterDic = @{@"chatroom_id":chatRoomID};
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    [manager POST:userJoinChatRoomUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
//        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
//        NSDictionary *statusDic = [responseObject valueForKey:@"status"];
//        NSString *msgString = [statusDic valueForKey:@"msg"];
//        if ([msgString isEqualToString:@"join in chatroom success"]) {
//           // [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertNoTitieWithContent:@"进入成功" toView:self];
//            MyChatViewController *myChatVC = [[MyChatViewController alloc] init];
//            myChatVC.conversationType = ConversationType_CHATROOM;
//            myChatVC.title = model.name;
//            myChatVC.targetId = chatRoomID;
//            [self.navigationController pushViewController:myChatVC animated:YES];
//        } else {
//           // [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertNoTitieWithContent:@"进入成功" toView:self];
//            MyChatViewController *myChatVC = [[MyChatViewController alloc] init];
//            myChatVC.conversationType = ConversationType_CHATROOM;
//            myChatVC.title = model.name;
//            myChatVC.targetId = chatRoomID;
//            [self.navigationController pushViewController:myChatVC animated:YES];
//        }
//    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
//        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"加入聊天室失败，请重新加入" ToView:self];
//    }];
//   
    NSLog(@"名字：%@", model.name);
   
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    [tableView deselectRowAtIndexPath:indexPath animated:NO];
//    ChatRoomModel *model = self.chatRoomDataArray[indexPath.row];
//    
//    MyChatViewController *myChatVC = [[MyChatViewController alloc] init];
//    myChatVC.conversationType = ConversationType_CHATROOM;
//    myChatVC.title = model.name;
//    [self.navigationController pushViewController:myChatVC animated:YES];
//    NSLog(@"名字：%@", model.name);
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
